package core;

import log.ServerLogger;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import ui.ServerMainFrame;
import util.ServerCache;
import xml.MsgName;
import xml.RegisterMsg;
import xml.RequestBody;
import xml.ResponseBody;

public class ClientHandler  extends IoHandlerAdapter
{
	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		ServerLogger.Error("上位机-服务器发生异常："+ cause.toString()+"/"+cause.getMessage()+"/"+cause.getStackTrace().toString());
		if(session.isConnected())
		{
			session.close();
			ServerLogger.Error("上位机-连接发生异常");
		}
		
	}
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception
	{
		ResponseBody responseBody = (ResponseBody) message;

		if(responseBody.getType().equals("heartbeat_response"))
		{
			//ServerLogger.DEBUG("来自上位机心跳");
		}else
		{
			ServerCache servercache = ServerCache.getInstance();
			IoSession sess = servercache.getUserConnectMap().get(responseBody.getReciever());

			if (sess.isConnected()) 
			{  
				sess.write(message);
			}
		}

		//ServerLogger.DEBUG("来自上位机:"+message);
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception
	{
		ServerLogger.DEBUG("发送到上位机: "+message);
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception
	{
		//String register = new RegisterMsg().createDocument("123456", "192.168.0.22", "v-0.1", "6125");
		//session.write(register);
	}
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		/*
		RequestBody body = new RequestBody();
		body.setType("heartbeat_request");
		body.setSender("0");
		body.setReciever("0");
		session.write(body);
		 */
	}
	public void sessionClosed(IoSession session) throws Exception {
		Client client = Client.getInstance();
		ServerLogger.INFO("与上位机连接关闭");
		client.startClient();
	}

}
